<?php
namespace addons\upload\controller;

use think\addons\Controller;
use addons\upload\model\UploadFile as UploadFileModel;
use hema\storage\Driver as StorageDriver;

/**
 * 文件库管理
 */
class Upload extends Controller
{
    /**
     * 图片上传接口
     */
    public function image()
    {
        $applet_id = $this->request->param('applet_id',0);
        $groupId = $this->request->param('groupId',0);
        $config = get_addons_config('upload');
        // 实例化存储驱动
        $storage = new StorageDriver($config['storage']);
        // 设置上传文件的信息
        $storage->setUploadFile('iFile')
            ->setValidationScene('image')
            ->upload();
        // 执行文件上传
        if (!$storage->upload()) {
            return $this->renderError('图片上传失败：' . $storage->getError());
        }
        // 文件信息
        $fileInfo = $storage->getSaveFileInfo();
        $fileInfo['group_id'] = $groupId;
        $fileInfo['file_type'] = 'image';
        $fileInfo['applet_id'] = $applet_id;
        // 添加文件库记录
        $model = new UploadFileModel;
        if($model->add($fileInfo)){
            $uploadFile = UploadFileModel::get($model->file_id);
            // 图片上传成功
            die(json_encode(['code' => 1, 'msg' => '上传成功', 'data' => $uploadFile]));
        }
        die(json_encode(['code' => 0, 'msg' => '上传失败', 'data' => []]));
    }
}
